<template>
  <div class="trade-settings-container">
    <el-card class="settings-card" :loading="tradeSettingsLoading">
      <template #header>
        <div class="card-header">
          <el-icon><Setting /></el-icon>
          <span>交易设置</span>
        </div>
      </template>
      
      <!-- 使用两列布局更好地利用空间 -->
      <div class="trade-settings-flex-container">
        <!-- 左列 - 基本设置表单 -->
        <div class="trade-settings-column">
          <el-form :model="tradeSettings" label-width="160px" class="trade-settings-form">
            <!-- 基础设置 -->
            <div class="section-header">
              <h3 class="settings-section-title">基础设置</h3>
            </div>
            
            <el-form-item label="开启交易">
              <el-switch
                v-model="tradeSettings.trade_switch"
                active-text="开启"
                inactive-text="关闭"
                @change="handleTradeSystemSwitch"
              />
            </el-form-item>
            
            <el-form-item label="开启注册">
              <el-switch
                v-model="tradeSettings.registration_switch"
                active-text="开启"
                inactive-text="关闭"
                @change="handleRegistrationSystemSwitch"
              />
            </el-form-item>
            
            <!-- 费用设置 -->
            <div class="section-header">
              <h3 class="settings-section-title">费用设置</h3>
              <el-button
                type="primary"
                text
                @click="setTradeFee"
              >
                <el-icon><RefreshRight /></el-icon>
                刷新缓存
              </el-button>
            </div>
            
            <!-- 交易手续费 -->
            <el-form-item label="交易手续费">
              <el-input-number
                v-model="tradeSettings.commission"
                :min="0"
                :max="100"
                :precision="2"
                :step="0.1"
              />
              <span class="unit-label">%</span>
              <span class="setting-tip">卖家需要支付的交易手续费</span>
            </el-form-item>
            
            <!-- 交易限制 -->
            <div class="section-header">
              <h3 class="settings-section-title">交易限制</h3>
              <el-button
                type="primary"
                text
                @click="saveTradeSettings" 
                title="更新交易限制"
              >
                <el-icon><RefreshRight /></el-icon>
                刷新缓存
              </el-button>
            </div>

            <!-- 精灵上架上限 -->
            <el-form-item label="精灵上架上限">
              <el-input-number
                v-model="tradeSettings.user_can_listing_pet_num"
                :min="0"
              />
              <span class="setting-tip">数量</span>
            </el-form-item>

            <!-- 道具上架上限 -->
            <el-form-item label="道具上架上限">
              <el-input-number
                v-model="tradeSettings.user_can_listing_item_num"
                :min="0"
              />
              <span class="setting-tip">种类</span>
            </el-form-item>
            
            <el-form-item label="交易后精灵冷却时间"> 
              <el-input-number
                v-model="tradeSettings.trade_after_pet_cool"
                :min="0"
              />
              <span class="unit-label">天</span>
            </el-form-item>

            <!-- 物品上架时间 -->
            <el-form-item label="物品上架时间">
              <el-input-number
                v-model="tradeSettings.trade_item_expire"
                :min="1"
                :max="30"
              />
              <span class="unit-label">天</span>
            </el-form-item>

            <!-- 交易行任务保留在这里 -->
            <el-form-item label="交易行任务">
              <el-select-v2
                v-model="tradeSettings.can_sell_task_spt"
                filterable
                :options="options"
                placeholder="选择交易行任务"
                style="width: 240px"
                multiple
                collapse-tags
                collapse-tags-tooltip
              />
              <span class="setting-tip">玩家完成交易任务才可以交易</span>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 右列 - 白名单管理 -->
        <div class="trade-settings-column">
          <!-- 上架白名单 -->
          <div class="trade-whitelist-container">
            <div class="section-header">
              <h3 class="settings-section-title" style="margin-top: 0px;">物品白名单</h3>
            </div>
            
            <!-- 搜索框和添加框 -->
            <div class="whitelist-controls" style="display: flex; gap: 12px; margin-bottom: 16px; align-items: center;">
              <!-- 搜索框 -->
              <el-input
                v-model="keyword"
                placeholder="搜索物品名称或ID"
                style="width: 200px;"
                clearable
                @input="handleWhitelistSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <!-- 添加物品选择器 -->
              <el-select
                v-model="selectedWhitelistItem"
                filterable
                remote
                placeholder="输入物品ID搜索后添加"
                :remote-method="searchItemsForWhitelist"
                :loading="whitelistItemSearchLoading"
                style="width: 220px;"
                @input="handleInputChange"
              >
                <!-- 改进空状态插槽逻辑 -->
                <template #empty>
                  <div v-if="whitelistItemSearchLoading || isUserTyping" class="search-loading-container">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    <span>正在搜索物品...</span>
                  </div>
                  <p v-else-if="hasSearched && whitelistItemSearchResults.length === 0">
                    未找到相关物品
                  </p>
                  <p v-else>
                    请输入物品ID进行搜索
                  </p>
                </template>
                
                <el-option
                  v-for="item in whitelistItemSearchResults"
                  :key="item.id"
                  :label="`${item.name} (ID: ${item.id})`"
                  :value="item.id"
                >
                  <div style="display: flex; justify-content: space-between;">
                    <span style="margin-right: 15px;">{{ item.name }}</span>
                    <span style="color: #8492a6; font-size: 13px">ID: {{ item.id }}</span>
                  </div>
                </el-option>
              </el-select>
              
              <!-- 添加按钮 -->
              <el-button 
                type="primary"
                @click="addItemToTradeWhitelist" 
                :disabled="!selectedWhitelistItem"
                :loading="addingWhitelistItem"
              >
                添加
              </el-button>
              
              <!-- 在右侧添加刷新缓存按钮，绑定到refreshWhiteList函数 -->
              <div style="flex-grow: 1; display: flex; justify-content: flex-end;">
                <el-button
                  type="primary"
                  text
                  @click="refreshWhiteList"
                  :loading="refreshingWhitelist"
                >
                  <el-icon><RefreshRight /></el-icon>
                  刷新缓存
                </el-button>
              </div>
            </div>
            
            <el-table 
              :data="filteredWhitelistItems"
              border 
              style="width: 100%; margin-top: 16px;"
              max-height="400px"
              v-loading="whitelistLoading"
            >
              <el-table-column prop="itemId" label="物品ID" width="100" />
              <el-table-column prop="itemName" label="物品名称" />
              <el-table-column prop="price" label="回收最低价格" width="150">
                <template #default="scope">
                  <div v-if="!scope.row.isEditing" style="display: flex; align-items: center; gap: 8px; cursor: pointer;" @click="startEditPrice(scope.row)">
                    <span v-if="scope.row.price" class="price-display">
                      {{ scope.row.price }} XIN
                    </span>
                    <span v-else class="price-placeholder">未设置</span>
                  </div>
                  <div v-else style="display: flex; align-items: center; gap: 8px;">
                    <el-input
                      v-model="scope.row.tempPrice"
                      type="number"
                      size="small"
                      placeholder="请输入价格"
                      style="width: 120px;"
                      class="no-spinner"
                      @keyup.enter="handlePriceBlur(scope.row)"
                      @blur="handlePriceBlur(scope.row)"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="添加时间" width="180">
                <template #default="scope">
                  {{ new Date(scope.row.createAt).toLocaleString('zh-CN') }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    size="small"
                    @click="removeItemFromTradeWhitelist(scope.row)"
                    :loading="removingWhitelistItem"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 修改分页控件，关联到API的分页参数 -->
            <div class="pagination-container" style="margin-top: 16px;">
              <el-pagination
                v-model:current-page="whitelistCurrentPage"
                v-model:page-size="whitelistPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="whitelistTotalItems"
                @size-change="handleWhitelistSizeChange"
                @current-change="handleWhitelistPageChange"
                background
              />
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>


</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Setting, Plus, RefreshRight, Loading, Search
} from '@element-plus/icons-vue'
import {
  getItemInfo,
  switchTradeSystem,
  getGlobalConfig,
  setTradeSetting,
  setFee,
  switchRegistrationSystem,
  getWhiteList,
  removeWhiteList,
  refreshWhiteListCache,
  addWhiteList,
  setRecyclePrice
} from '@/api/system'
import { secondsToDays, calculateRemainingAmount, daysToSeconds, calculateRemainingRatio } from '@/utils/utils'

// 添加防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 交易设置加载状态
const tradeSettingsLoading = ref(false)
const tradeConfigLoading = ref(false)

// 交易设置相关数据
const tradeSettings = reactive({
  trade_switch: true,     // 交易行开关（1-开，0-关）
  registration_switch: true, // 注册系统开关（1-开，0-关）
  commission: 0,     // 交易行手续费
  user_can_listing_pet_num: 0,     // 用户可以上架宠物种类
  user_can_listing_item_num: 0,     // 用户可以上架道具种类
  trade_item_expire: 0,     // 交易行上架物品过期时间（天）
  trade_after_pet_cool: 0,     // 交易后精灵冷却时间（秒）
  whitelist: [],     // 交易白名单
  can_sell_task_spt: []     // 交易行任务
})

// 交易行任务选项
const options = [
  { value: 301, label: '蘑菇怪' },
  { value: 302, label: '钢牙鲨' },
  { value: 303, label: '里奥斯‌' },
  { value: 304, label: '提亚斯' },
  { value: 305, label: '阿克西亚' },
  { value: 306, label: '雷伊' },
  { value: 307, label: '纳多雷' },
  { value: 308, label: '雷纳多' },
  { value: 309, label: '尤纳斯‌' },
  { value: 310, label: '魔狮迪露' },
  { value: 311, label: '哈默雷特' },
  { value: 312, label: '奈尼芬多' },
  { value: 99, label: '盖亚' }
]

// 白名单相关数据
const selectedWhitelistItem = ref(null)
const whitelistItemSearchResults = ref([])
const whitelistItemSearchLoading = ref(false)
const hasSearched = ref(false)
const isUserTyping = ref(false)
const keyword = ref('')
const filteredWhitelistItems = ref([])

// 白名单分页相关变量
const whitelistCurrentPage = ref(1)
const whitelistPageSize = ref(10)
const whitelistTotalItems = ref(0)
const whitelistItems = ref([])
const whitelistLoading = ref(false)

// 首先添加一个新的ref变量来跟踪添加操作的加载状态
const addingWhitelistItem = ref(false) // 添加白名单项的加载状态
const removingWhitelistItem = ref(false) // 移除白名单项的加载状态
const refreshingWhitelist = ref(false)  // 刷新白名单缓存的加载状态



// 加载全局配置
const loadGlobalConfig = async () => {
  try {
    // 显示加载动画
    tradeSettingsLoading.value = true
    
    // 调用API获取全局配置
    const response = await getGlobalConfig()
    
    if (response.code === 200 && response.data) {
      const data = response.data
      
      // 注意后端返回的是字符串，需要进行适当的类型转换
      if (data.TRADE_SWITCH !== undefined) {
        tradeSettings.trade_switch = data.TRADE_SWITCH === '1' || data.TRADE_SWITCH === 'true'
      }
      
      if (data.REGISTER_SWITCH !== undefined) {
        tradeSettings.registration_switch = data.REGISTER_SWITCH	 === '1' 
      }
      
      if (data.COMMISSION !== undefined) {
        tradeSettings.commission = calculateRemainingAmount(data.COMMISSION) || 0
      }
      
      if (data.USER_CAN_LISTING_PET_NUM !== undefined) {
        tradeSettings.user_can_listing_pet_num = parseInt(data.USER_CAN_LISTING_PET_NUM) || 0
      }
      
      if (data.USER_CAN_LISTING_ITEM_NUM !== undefined) {
        tradeSettings.user_can_listing_item_num = parseInt(data.USER_CAN_LISTING_ITEM_NUM) || 0
      }
      
      if (data.TRADE_ITEM_EXPIRE !== undefined) {
        tradeSettings.trade_item_expire = parseInt(data.TRADE_ITEM_EXPIRE) || 0
      }
      
      if (data.TRADE_AFTER_PET_COOL !== undefined) {
        tradeSettings.trade_after_pet_cool = secondsToDays(data.TRADE_AFTER_PET_COOL) || 0
      }
      
      if (data.CAN_SELL_TASK_SPT !== undefined) {
        try {
          if (typeof data.CAN_SELL_TASK_SPT === 'string') {
            // 首先尝试作为JSON解析
            try {
              tradeSettings.can_sell_task_spt = JSON.parse(data.CAN_SELL_TASK_SPT)
            } catch (e) {
              // 如果JSON解析失败，尝试作为逗号分隔字符串解析
              const taskArray = data.CAN_SELL_TASK_SPT.split(',')
                .filter(task => task.trim() !== '')
                .map(task => task.trim())
              
              tradeSettings.can_sell_task_spt = taskArray
            }
          } else if (Array.isArray(data.CAN_SELL_TASK_SPT)) {
            tradeSettings.can_sell_task_spt = data.CAN_SELL_TASK_SPT
          }
        } catch (error) {
          console.error('解析CAN_SELL_TASK_SPT失败:', error)
          tradeSettings.can_sell_task_spt = []
        }
      }
      
      // 处理白名单
      if (data.WHITELIST !== undefined) {
        try {
          if (typeof data.WHITELIST === 'string') {
            tradeSettings.whitelist = JSON.parse(data.WHITELIST)
          } else {
            tradeSettings.whitelist = data.WHITELIST || []
          }
        } catch (error) {
          console.error('解析WHITELIST失败:', error)
          tradeSettings.whitelist = []
        }
      }
      
      ElMessage.success('交易系统配置加载成功')
    } else {
      ElMessage.error(response.msg || '获取系统配置失败')
    }
  } catch (error) {
    console.error('加载交易系统配置失败:', error)
    ElMessage.error('加载交易系统配置失败')
  } finally {
    // 无论成功还是失败，都隐藏加载动画
    tradeSettingsLoading.value = false
  }
}

// 保存交易设置
const saveTradeSettings = async () => {
  try {
    // 显示加载动画
    tradeConfigLoading.value = true
    
    // 准备交易设置数据
    const tradeData = {
      USER_CAN_LISTING_PET_NUM: String(tradeSettings.user_can_listing_pet_num),
      USER_CAN_LISTING_ITEM_NUM: String(tradeSettings.user_can_listing_item_num),
      TRADE_ITEM_EXPIRE: String(tradeSettings.trade_item_expire),
      // 将天数转换为秒数
      TRADE_AFTER_PET_COOL: String(daysToSeconds(tradeSettings.trade_after_pet_cool)),
      // 将数组转换为字符串
      CAN_SELL_TASK_SPT: JSON.stringify(tradeSettings.can_sell_task_spt),
      // 添加其他可能需要的字段
      COMMISSION: String(calculateRemainingRatio(tradeSettings.commission)),
      TRADE_SWITCH: tradeSettings.trade_switch ? '1' : '0',
      REGISTRATION_SWITCH: tradeSettings.registration_switch ? '1' : '0'
    }
    
    // 调用API保存交易设置
    const response = await setTradeSetting(tradeData)
    
    if (response.code === 200) {
      ElMessage.success('交易设置保存成功')
    } else {
      ElMessage.error(response.msg || '保存交易设置失败')
    }
  } catch (error) {
    console.error('保存交易设置失败:', error)
    ElMessage.error('保存交易设置失败')
  } finally {
    // 隐藏加载动画
    tradeConfigLoading.value = false
  }
}

// 设置交易手续费
const setTradeFee = async () => {
  const response = await setFee(calculateRemainingRatio(tradeSettings.commission))
  if (response.code === 200) {
    ElMessage.success('交易手续费设置成功')
  } else {
    ElMessage.error(response.msg || '设置交易手续费失败')
  }
}

// 处理交易系统开关切换
const handleTradeSystemSwitch = async (value) => {
  try {
    const response = await switchTradeSystem(value)
    if (response.code === 200) {
      ElMessage.success(`交易系统已${value ? '开启' : '关闭'}`)
    } else {
      // 如果API调用失败，恢复开关状态
      tradeSettings.trade_switch = !value
      ElMessage.error(response.msg || `${value ? '开启' : '关闭'}交易系统失败`)
    }
  } catch (error) {
    console.error('切换交易系统状态出错:', error)
    // 如果发生异常，恢复开关状态
    tradeSettings.trade_switch = !value
    ElMessage.error(`${value ? '开启' : '关闭'}交易系统失败`)
  }
}

// 处理注册系统开关切换
const handleRegistrationSystemSwitch = async (value) => {
  try {
    const response = await switchRegistrationSystem(value)
    if (response.code === 200) {
      ElMessage.success(`注册系统已${value ? '开启' : '关闭'}`)
    } else {
      // 如果API调用失败，恢复开关状态
      tradeSettings.registration_switch = !value
      ElMessage.error(response.msg || `${value ? '开启' : '关闭'}注册系统失败`)
    }
  } catch (error) {
    console.error('切换注册系统状态出错:', error)
    // 如果发生异常，恢复开关状态
    tradeSettings.registration_switch = !value
    ElMessage.error(`${value ? '开启' : '关闭'}注册系统失败`)
  }
}

// 重置交易设置
const resetTradeSettings = () => {
  Object.assign(tradeSettings, {
    trade_switch: true,     // 交易行开关（1-开，0-关）
    registration_switch: true, // 注册系统开关（1-开，0-关）
    commission: 0,     // 交易行手续费
    user_can_listing_pet_num: 0,     // 用户可以上架宠物种类
    user_can_listing_item_num: 0,     // 用户可以上架道具种类
    trade_item_expire: 0,     // 交易行上架物品过期时间（天）
    trade_after_pet_cool: 0,     // 交易后精灵冷却时间（秒）
    whitelist: [],     // 交易白名单
    can_sell_task_spt: []     // 交易行任务
  })
  ElMessage.info('交易设置已重置')
}

// 加载白名单数据的函数
const loadWhiteListData = async () => {
  try {
    whitelistLoading.value = true
    const params = {
      currentPage: whitelistCurrentPage.value,
      limit: whitelistPageSize.value
    }
    
    // 如果keyword有值，则添加到请求参数中
    if (keyword.value) {
      params.keyword = keyword.value
    }
    
    const response = await getWhiteList(params)
    
    if (response.code === 200 && response.data) {
      // 为每个白名单项添加price字段，对应回收最低价格
      const processedList = (response.data.list || []).map(item => ({
        ...item,
        price: item.price || 0 // 添加price字段对应回收最低价格
      }))
      
      whitelistItems.value = processedList
      whitelistTotalItems.value = response.data.totalCount
      
      // 直接使用API返回的数据
      filteredWhitelistItems.value = processedList
    } else {
      ElMessage.error(response.msg || '获取白名单数据失败')
    }
  } catch (error) {
    console.error('加载白名单数据失败:', error)
    ElMessage.error('加载白名单数据失败')
  } finally {
    whitelistLoading.value = false
  }
}

// 处理搜索输入
const handleWhitelistSearch = () => {
  whitelistCurrentPage.value = 1 // 搜索时重置到第一页
  loadWhiteListData()
}

// 处理白名单分页大小变化
const handleWhitelistSizeChange = (size) => {
  whitelistPageSize.value = size
  whitelistCurrentPage.value = 1 // 重置到第一页
  loadWhiteListData()
}

// 处理白名单页码变化
const handleWhitelistPageChange = (page) => {
  whitelistCurrentPage.value = page
  loadWhiteListData()
}

// 监听白名单变化更新总条目数
watch(() => tradeSettings.whitelist, (newValue) => {
  whitelistTotalItems.value = newValue.length
}, { immediate: true })

// 监听搜索关键词变化
// watch(keyword, (newValue, oldValue) => {
//   // 当搜索关键词发生变化时，重置到第一页并重新加载数据
//   whitelistCurrentPage.value = 1
//   loadWhiteListData()
// })

// 处理搜索框输入变化
const handleInputChange = (val) => {
  if (val) {
    // 用户正在输入，立即设置状态
    isUserTyping.value = true
    whitelistItemSearchLoading.value = true
  } else {
    isUserTyping.value = false
    whitelistItemSearchLoading.value = false
    hasSearched.value = false
  }
}

// 优化防抖搜索方法
const searchItemsForWhitelist = debounce((query) => {
  if (!query) {
    whitelistItemSearchResults.value = []
    hasSearched.value = false
    whitelistItemSearchLoading.value = false
    isUserTyping.value = false
    return
  }
  
  // 执行实际搜索
  searchItems(query)
}, 300)

// 搜索物品
const searchItems = async (query) => {
  if (!query) {
    whitelistItemSearchResults.value = []
    hasSearched.value = false
    isUserTyping.value = false
    return
  }

  try {
    // 使用项目API模块调用搜索物品
    const response = await getItemInfo(query)
    
    if (response && response.code === 200) {
      // 单个物品结果
      const item = {
        id: response.id,
        name: response.name,
        type: response.type
      }
      whitelistItemSearchResults.value = [item]
    } else {
      // API可能返回了错误或没有结果
      whitelistItemSearchResults.value = []
    }
  } catch (error) {
    console.error('搜索物品失败:', error)
    whitelistItemSearchResults.value = []
    ElMessage.error('搜索物品失败，请检查ID是否正确')
  } finally {
    // 设置搜索已完成标志
    hasSearched.value = true
    isUserTyping.value = false
    
    // 延迟关闭加载状态
    setTimeout(() => {
      whitelistItemSearchLoading.value = false
    }, 200)
  }
}

// 添加物品到交易白名单 - 实现API调用
const addItemToTradeWhitelist = async () => {
  if (!selectedWhitelistItem.value) return
  
  const selectedItem = whitelistItemSearchResults.value.find(
    item => item.id === selectedWhitelistItem.value
  )
  
  if (!selectedItem) return
  
  // 设置加载状态为true
  addingWhitelistItem.value = true
  
  try {
    // 调用添加白名单API
    const response = await addWhiteList({
      itemId: selectedItem.id,
      itemName: selectedItem.name
    })
    
    if (response.code === 200) {
      // 添加成功后重新加载白名单数据
      await loadWhiteListData()
      selectedWhitelistItem.value = null
      ElMessage.success(`已将物品 ${selectedItem.name} (ID: ${selectedItem.id}) 添加到白名单`)
    } else {
      ElMessage.error(response.msg || '添加白名单项失败')
    }
  } catch (error) {
    console.error('添加白名单项失败:', error)
    ElMessage.error('添加白名单项失败')
  } finally {
    // 无论成功还是失败，都关闭加载状态
    addingWhitelistItem.value = false
  }
}

// 从交易白名单移除物品 - 更新为显示加载状态
const removeItemFromTradeWhitelist = async (item) => {
  removingWhitelistItem.value = true
  try {
    const response = await removeWhiteList(item.itemId)
    
    if (response.code === 200) {
      // 移除成功后重新加载白名单数据
      await loadWhiteListData()
      ElMessage.success(`已将物品 ${item.itemName} 从白名单移除`)
    } else {
      ElMessage.error(response.msg || '移除白名单项失败')
    }
  } catch (error) {
    console.error('移除白名单项失败:', error)
    ElMessage.error('移除白名单项失败')
  } finally {
    removingWhitelistItem.value = false
  }
}

// 刷新白名单缓存 - 更新为显示加载状态
const refreshWhiteList = async () => {
  refreshingWhitelist.value = true
  try {
    const response = await refreshWhiteListCache()
    
    if (response.code === 200) {
      // 刷新缓存后重新加载白名单数据
      await loadWhiteListData()
      ElMessage.success('白名单缓存已刷新')
    } else {
      ElMessage.error(response.msg || '刷新白名单缓存失败')
    }
  } catch (error) {
    console.error('刷新白名单缓存失败:', error)
    ElMessage.error('刷新白名单缓存失败')
  } finally {
    refreshingWhitelist.value = false
  }
}

// 更新回收最低价格
const updateMinRecyclePrice = async (item, newPrice) => {
  try {
    // 这里需要调用API来更新价格
    // await updateItemMinRecyclePrice(item.id, newPrice)
    
    // 更新本地数据
    item.minRecyclePrice = newPrice
    
    ElMessage.success('价格更新成功')
  } catch (error) {
    console.error('更新价格失败:', error)
    ElMessage.error('价格更新失败')
  }
}

// 开始编辑价格
const startEditPrice = (item) => {
  item.isEditing = true
  item.tempPrice = item.price || 0
  
  // 使用nextTick确保DOM更新后再聚焦
  nextTick(() => {
    // 使用setTimeout确保DOM完全渲染
    setTimeout(() => {
      // 查找当前正在编辑的输入框
      const editingInput = document.querySelector('.no-spinner input')
      if (editingInput) {
        editingInput.focus()
        editingInput.select()
      }
    }, 10)
  })
}

// 取消价格编辑
const cancelPriceEdit = (item) => {
  item.isEditing = false
  item.tempPrice = item.price || 0
}

// 处理价格输入框失去焦点
const handlePriceBlur = async (item) => {
  // 如果没有输入内容或输入内容为空或为0，则退出编辑状态
  if (!item.tempPrice || item.tempPrice === '' || item.tempPrice === 0) {
    item.isEditing = false
    item.tempPrice = item.price || 0
    return
  }
  
  // 如果输入的价格与原价格相同，直接退出编辑状态
  if (item.tempPrice === item.price) {
    item.isEditing = false
    return
  }
  
  try {
    // 调用API来更新价格
    await setRecyclePrice({
      itemId: parseInt(item.itemId),
      price: parseInt(item.tempPrice)
    })
    
    // API调用成功，更新本地数据
    item.minRecyclePrice = item.tempPrice
    item.price = item.tempPrice
    item.isEditing = false
    
    ElMessage.success('价格更新成功')
  } catch (error) {
    console.error('更新价格失败:', error)
    ElMessage.error('价格更新失败')
    // 恢复原价格
    item.tempPrice = item.price || 0
    item.isEditing = false
  }
}

// 组件挂载时加载配置
onMounted(() => {
  loadGlobalConfig()
  loadWhiteListData() // 加载白名单数据
})
</script>

<style scoped>
.price-display {
  color: #409eff;
  font-weight: 500;
}

.price-placeholder {
  color: #c0c4cc;
  font-style: italic;
}

.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 0;
}

/* 交易限制表单项增加间距 */
.trade-settings-form .el-form-item {
  margin-bottom: 20px;
}

/* 交易限制表单最后一项不需要底部间距 */
.trade-settings-form .el-form-item:last-child {
  margin-bottom: 0;
}

/* 隐藏数字输入框的上下箭头 */
.no-spinner :deep(.el-input__inner) {
  -webkit-appearance: none;
  -moz-appearance: textfield;
}

.no-spinner :deep(.el-input__inner)::-webkit-outer-spin-button,
.no-spinner :deep(.el-input__inner)::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>

<style lang="scss" scoped>
.trade-settings-container {
  padding: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  
  .el-icon {
    margin-right: 8px;
  }
}

/* 交易设置相关样式 */
.trade-settings-flex-container {
  display: flex;
  gap: 24px;
  margin-top: 24px;
  
  .trade-settings-column {
    width: 50%;
    min-width: 0; /* 允许列宽压缩 */
  }
}

.trade-settings-form {
  width: 100%;
  
  .settings-section-title {
    margin: 24px 0 16px;
    padding-left: 8px;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-color-primary);
    border-left: 3px solid var(--el-color-primary);
  }
}

/* 单位标签样式 */
.unit-label, .setting-tip {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}

.setting-tip {
  font-size: 13px;
}

/* 白名单容器样式 */
.trade-whitelist-container {
  .whitelist-add-form {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
}

/* 搜索加载动画 */
.search-loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  color: var(--el-text-color-secondary);
  
  .el-icon {
    margin-right: 8px;
    font-size: 16px;
    animation: loading-rotate 1s linear infinite;
  }
}

@keyframes loading-rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 添加标题和刷新按钮的样式 */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  
  .settings-section-title {
    margin: 0;
  }
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 使首个标题顶部没有多余空白 */
.settings-section-title:first-of-type {
  margin-top: 0;
}
</style>